﻿using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.mIE.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mIE.UI
{
    public partial class Frm_IE_LaborDataUpload : frmBaseChild
    {
        DataTable dtProc_Type_Ctrl = new DataTable();
        DataTable dtTemp = new DataTable();
        DataTable dt = null;
        public Frm_IE_LaborDataUpload()
        {
            InitializeComponent();           
            dtTemp.Columns.Add("图纸号");
            dtTemp.Columns.Add("部件编号");
            dtTemp.Columns.Add("工序组");
            dtTemp.Columns.Add("计数器");
            dtTemp.Columns.Add("计数器描述");
            dtTemp.Columns.Add("序号");
            dtTemp.Columns.Add("工序代码");
            dtTemp.Columns.Add("工序工时(S)");
            dtTemp.Columns.Add("并行标识");          
        }
        public Frm_IE_LaborDataUpload(DataTable dt)
        {
            InitializeComponent();
            dtTemp.Columns.Add("图纸号");
            dtTemp.Columns.Add("部件编号");
            dtTemp.Columns.Add("工序组");
            dtTemp.Columns.Add("计数器");
            dtTemp.Columns.Add("计数器描述");
            dtTemp.Columns.Add("序号");
            dtTemp.Columns.Add("工序代码");
            dtTemp.Columns.Add("工序工时(S)");
            dtTemp.Columns.Add("并行标识");
            dtProc_Type_Ctrl = dt;

        }

        private void Frm_IE_LaborDataUpload_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            InitProductItem(dtProc_Type_Ctrl);
        }
        //产品类型初始化
        public void InitProductItem(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                this.txt_ProductItem.Properties.Items.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    this.txt_ProductItem.Properties.Items.Add(dt.Rows[i]["PROD_CATEGORY"].ToString());
                }
                txt_ProductItem.SelectIndex = 0;
                txt_ProductItem.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            }
            else
            {
                dt = BaseFactory<IE_Part_TaskList>.Instance.GetProductItem();
                this.txt_ProductItem.Properties.Items.Clear();
                if (dt.Rows.Count > 0)
                {
                    string[] list = dt.Rows[0]["FIELD_VALUE_OPTION"].ToString().Split(',');
                    foreach (var item in list)
                    {
                        this.txt_ProductItem.Properties.Items.Add(item);
                    }
                }
            }
            //DataTable dttemp = BaseFactory<IE_Part_TaskList>.Instance.GetProductItem();
            //this.txt_ProductItem.Properties.Items.Clear();
            //if (dttemp.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dttemp.Rows)
            //    {
            //        if (dr["FIELD_VALUE_OPTION"].ToString().Trim().Length > 0)
            //        {
            //            string[] arr = dr["FIELD_VALUE_OPTION"].ToString().Split(',');
            //            foreach (string s in arr)
            //            {
            //                this.txt_ProductItem.Properties.Items.Add(s);
            //            }

            //        }

            //    }
            //}
        }
        //查询
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            try
            {
                //  SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "数据正在刷新中......", new Size(400, 80)))
                {
                    string sqlWhere = "";
                    string sql = @"select T.PROD_CATEGORY,R.GROUP_CODE,T.DWG_NO,T.PART_NO,M.CN_DESC, F.PROCESS_CODE,SUM(ISNULL(F.LABOR_VALUE,0)) as LABOR_VALUE,F.UPDATE_USER,CONVERT(varchar(16), F.UPDATE_TIME,120) UPDATE_TIME  ,N.ALLOWANCE_FACTOR
                            FROM IE_Part_TaskList T
                            LEFT JOIN  IE_Part_FeatureList F on  F.PART_NO=T.PART_NO and f.DWG_NO=t.DWG_NO
                            LEFT　JOIN IE_Part_MasterData M ON M.PART_NO=T.PART_NO
                            LEFT　JOIN IE_Part_Routing R ON R.PART_NO=F.PART_NO and r.DWG_NO=t.DWG_NO
                            LEFT　JOIN  [dbo].[IE_WorkCenter_AllowanceFactor] N on N.PROCESS_CODE=F.PROCESS_CODE
                            WHERE T.FEAT_FLAG='1'  AND ISNULL(T.UPLOAD_FLAG,'')!= '1' and N.EXPIRY_DATE='9999-12-31'";
                    //AND ISNULL(T.CAL_FLAG,'')!= '1' AND ISNULL(T.UPLOAD_FLAG,'')!= '1'
                    if (!string.IsNullOrEmpty(txt_ProductItem.Text))
                    {
                        sqlWhere += " and T.PROD_CATEGORY like '%" + txt_ProductItem.Text + "%'";
                    }
                    if (!string.IsNullOrEmpty(txtFILE_NO.Text))
                    {
                        sqlWhere += " and T.FILE_NO like '%" + txtFILE_NO.Text + "%'";
                    }
                    StringBuilder sbDRAWING = new StringBuilder();
                    StringBuilder sbPARTNO = new StringBuilder();
                    string[] strdwg = memo_DWGNO.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    string[] strpartno = memo_PARTNO.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    if (strdwg[0].Length > 0)
                    {
                        sbDRAWING.AppendFormat(" AND T.DWG_NO IN('{0}') ", string.Join("','", strdwg.ToArray()));
                        sqlWhere += sbDRAWING.ToString();
                    }

                    if (strpartno[0].Length > 0)
                    {
                        sbPARTNO.AppendFormat(" AND T.PART_NO IN('{0}') ", string.Join("','", strpartno.ToArray()));
                        sqlWhere += sbPARTNO.ToString();
                    }

                    sql = sql + sqlWhere + " GROUP BY T.PROD_CATEGORY,R.GROUP_CODE,T.DWG_NO,T.PART_NO,M.CN_DESC, F.PROCESS_CODE,F.UPDATE_USER,CONVERT(varchar(16), F.UPDATE_TIME,120)  ,N.ALLOWANCE_FACTOR ORDER BY T.DWG_NO";
                    dt = BaseBuildSql.GetDataTableBySql(sql);
                    if (dt.Rows.Count <= 0)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("您所查询的数据不存在，请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // return;
                    }
                    gridControl1.DataSource = dt;
                    //this.gridView1.Columns["GROUP"].Visible = false;
                    //this.gridView1.Columns["TypeName"].Visible = false;
                    this.gridView1.OptionsView.ColumnAutoWidth = false;
                    gridView1.BestFitColumns();
                    //SplashScreenTool.CloseSplashScreen();
                }
            }
            catch (Exception EX)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(EX.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //SplashScreenTool.CloseSplashScreen();
            }
        }
        //上载
       
        public override void DoCalculate(Lamex.Interface.IButtonInfo sender)
        {
            
            base.DoCalculate(sender);
        }
        public override void DoIEExportUpLoad(IButtonInfo sender)
        {
            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            try
            {
                //if (gridView1.RowCount < 1)
                //{
                //    XtraMessageBox.Show("没有工时数据");
                //    return;
                //}
                string fileName = "ZPY3_UPLOAD.TXT";
                string path = @"C:\SAPTEMP\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = path + fileName;
                StringBuilder builder = new StringBuilder();
                builder.Append("部件编号" + "\t" + "工序组" + "\t" + "计数器"+ "\t" + "计数器描述" + "\t" + "序号" + "\t" + "工序代码" + "\t" + "工序工时(S)" + "\t" + "并行标识" + "\r\n");
                
                foreach (DataRow dr in dtTemp.Rows)
                {
                    builder.Append(dr["部件编号"] + "\t" + dr["工序组"] + "\t" + dr["计数器"] + "\t" + dr["计数器描述"] + "\t" + dr["序号"] + "\t" + dr["工序代码"] + "\t" + dr["工序工时(S)"] + "\t" + dr["并行标识"] + "\r\n");
                    
                }
                using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    using (System.IO.TextWriter text = new System.IO.StreamWriter(file, System.Text.Encoding.Default))
                    {
                        text.Write(builder.ToString());
                    }
                }
                //2020更改数据--
                DataView dv = new DataView(dtTemp);
                DataTable dtList = dv.ToTable(true, new string[] { "部件编号" });
                foreach(DataRow disRow in dtList.Rows)
                {
                    DataTable dt = BaseBuildSql.GetDataTableBySql("select * from IE_Part_ProcessTime where 1=1 and PART_NO='" + disRow["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EFFECTIVE_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',120)");
                    if(dt.Rows.Count!=0)
                    {
                        int m = BaseBuildSql.ExecuteNonQuery("delete from  IE_Part_ProcessTime where  PART_NO='" + disRow["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EFFECTIVE_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',120)");
                        if(m>0)
                        {
                            DataRow[] drows = dtTemp.Select(" 1=1 and 部件编号='" + disRow["部件编号"].ToString() + "'");
                            if (drows != null)
                            {
                                foreach (DataRow dr in drows)
                                {
                                    builder.Append(dr["部件编号"] + "\t" + dr["工序组"] + "\t" + dr["计数器"] + "\t" + dr["计数器描述"] + "\t" + dr["序号"] + "\t" + dr["工序代码"] + "\t" + dr["工序工时(S)"] + "\t" + dr["并行标识"] + "\r\n");
                                    BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                                    values('" + dr["图纸号"].ToString() + "','" + dr["部件编号"] + "','" + dr["工序组"].ToString() + "','" + dr["计数器"].ToString() + "','" + dr["序号"].ToString() + "','" + dr["工序代码"] + "','" + dr["工序工时(S)"] + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Lamex.Common.Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + DateTime.MaxValue + "','" + DateTime.Now.ToString("yyyyMMdd") + "')");
                                }
                            }
                        }
                    }
                    else
                    {
                        DataTable dtsub = BaseBuildSql.GetDataTableBySql("select * from IE_Part_ProcessTime where  PART_NO='" + disRow["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EXPIRY_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.MaxValue.ToString("yyyy-MM-dd HH:mm:ss") + "',120)");
                        if (dtsub.Rows.Count != 0)
                        {
                            BaseBuildSql.ExecuteNonQuery("update IE_Part_ProcessTime set EXPIRY_DATE='" + DateTime.Now.AddDays(-1) + "' where  PART_NO='" + disRow["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EXPIRY_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.MaxValue.ToString("yyyy-MM-dd HH:mm:ss") + "',120)");

                            DataRow[] drows = dtTemp.Select(" 1=1 and 部件编号='" + disRow["部件编号"].ToString() + "'");
                            if (drows != null)
                            {
                                foreach (DataRow dr in drows)
                                {
                                    builder.Append(dr["部件编号"] + "\t" + dr["工序组"] + "\t" + dr["计数器"] + "\t" + dr["计数器描述"] + "\t" + dr["序号"] + "\t" + dr["工序代码"] + "\t" + dr["工序工时(S)"] + "\t" + dr["并行标识"] + "\r\n");
                                    BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                                    values('" + dr["图纸号"].ToString() + "','" + dr["部件编号"] + "','" + dr["工序组"].ToString() + "','" + dr["计数器"].ToString() + "','" + dr["序号"].ToString() + "','" + dr["工序代码"] + "','" + dr["工序工时(S)"] + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Lamex.Common.Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + DateTime.MaxValue + "','" + DateTime.Now.ToString("yyyyMMdd") + "')");
                                }
                            }

                        }
                        else
                        {
                            DataRow[] drows = dtTemp.Select(" 1=1 and 部件编号='" + disRow["部件编号"].ToString() + "'");
                            if (drows != null)
                            {
                                foreach (DataRow dr in drows)
                                {
                                    builder.Append(dr["部件编号"] + "\t" + dr["工序组"] + "\t" + dr["计数器"] + "\t" + dr["计数器描述"] + "\t" + dr["序号"] + "\t" + dr["工序代码"] + "\t" + dr["工序工时(S)"] + "\t" + dr["并行标识"] + "\r\n");
                                    BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                                    values('" + dr["图纸号"].ToString() + "','" + dr["部件编号"] + "','" + dr["工序组"].ToString() + "','" + dr["计数器"].ToString() + "','" + dr["序号"].ToString() + "','" + dr["工序代码"] + "','" + dr["工序工时(S)"] + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Lamex.Common.Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + DateTime.MaxValue + "','" + DateTime.Now.ToString("yyyyMMdd") + "')");
                                }
                            }
                        }
                    }

                    BaseBuildSql.ExecuteNonQuery("update IE_Part_TaskList  set CAL_FLAG = 1 where PART_NO ='" + disRow["部件编号"] + "'");
                }

                #region"remove"
                //foreach (DataRow dr in dtTemp.Rows)
                //{
                //    builder.Append(dr["部件编号"] + "\t" + dr["工序组"] + "\t" + dr["计数器"] + "\t" + dr["计数器描述"] + "\t" + dr["序号"] + "\t" + dr["工序代码"] + "\t" + dr["工序工时(S)"] + "\t" + dr["并行标识"] + "\r\n");

                //    DataTable dt = BaseBuildSql.GetDataTableBySql("select * from IE_Part_ProcessTime where PROCESS_CODE='"+ dr["工序代码"] .ToString()+ "' and PART_NO='" + dr["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EFFECTIVE_DATE,120)=CONVERT(nvarchar(10), '"+DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")+"',120)");
                //    if(dt.Rows.Count!=0)
                //    {
                //       int m = BaseBuildSql.ExecuteNonQuery("delete from  IE_Part_ProcessTime where PROCESS_CODE='" + dr["工序代码"].ToString() + "' and PART_NO='" + dr["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EFFECTIVE_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "',120)");
                //        if(m>0)
                //        {
                //            BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                //            values('" + dr["图纸号"].ToString() + "','"+ dr["部件编号"] + "','" + dr["工序组"].ToString()+ "','"+ dr["计数器"].ToString()+ "','" + dr["序号"].ToString()+ "','" + dr["工序代码"] + "','"+ dr["工序工时(S)"] + "','"+DateTime.Now+"','"+Lamex.Common.Loginer.CurrentUser.Account+"','"+DateTime.Now+"','"+DateTime.MaxValue+ "','" + DateTime.Now.ToString("yyyyMMdd") + "')");
                //        }
                //    }
                //    else
                //    {
                //        DataTable dtsub = BaseBuildSql.GetDataTableBySql("select * from IE_Part_ProcessTime where PROCESS_CODE='" + dr["工序代码"].ToString() + "' and PART_NO='" + dr["部件编号"].ToString() + "' and  CONVERT(nvarchar(10), EXPIRY_DATE,120)=CONVERT(nvarchar(10), '" + DateTime.MaxValue.ToString("yyyy-MM-dd hh:mm:ss") + "',120)");
                //        if(dtsub.Rows.Count!=0)
                //        {


                //            BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                //            values('" + dr["图纸号"].ToString() + "','" + dr["部件编号"] + "','" + dr["工序组"].ToString() + "','" + dr["计数器"].ToString() + "','" + dr["序号"].ToString() + "','" + dr["工序代码"] + "','" + dr["工序工时(S)"] + "','" + DateTime.Now + "','" + Lamex.Common.Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + DateTime.MaxValue + "','" + DateTime.Now.ToString("yyyyMMdd") + "')");
                //        }
                //        else
                //        {
                //            BaseBuildSql.ExecuteNonQuery(@"insert into IE_Part_ProcessTime(DWG_NO,PART_NO,GROUPS,COUNTER,SEQUENCE_NO,PROCESS_CODE,PROCESS_TIME,CAL_TIME,CAL_USER,EFFECTIVE_DATE,EXPIRY_DATE,SAP_VERSION)
                //            values('" + dr["图纸号"].ToString() + "','" + dr["部件编号"] + "','" + dr["工序组"].ToString() + "','" + dr["计数器"].ToString() + "','" + dr["序号"].ToString() + "','" + dr["工序代码"] + "','" + dr["工序工时(S)"] + "','" + DateTime.Now + "','" + Lamex.Common.Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + DateTime.MaxValue + "','"+DateTime.Now.ToString("yyyyMMdd")+"')");
                //        }
                //    }
                //    BaseBuildSql.ExecuteNonQuery("update IE_Part_TaskList  set CAL_FLAG = 1 where PART_NO ='" + dr["部件编号"] + "'");
                //}
                #endregion
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show("【成功导出数据,请登陆SAP用ZPY3执行上载IE标准工时！】");
                gridControl1.DataSource = null;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                SplashScreenTool.CloseSplashScreen();
            }
            base.DoIEExportUpLoad(sender);
        }

        public override void DoIECalcuate(IButtonInfo sender)
        {
            try
            {

                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                
                DataTable dtresult = Common.GetTable.GetTable_LaborUpLoad();//定义界面显示表
                DataTable dtRouting = Common.GetTable.GetTable_Routing_JM();
                DataRow drRouting = dtRouting.NewRow();//路线代码组输出表
                DataTable dtSerial_Laminate = BaseBuildSql.GetDataTableBySql(@"SELECT  IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '44%' ");
                DataTable dtSerial_Panel = BaseBuildSql.GetDataTableBySql(@"SELECT   IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '43%' ");
                DataTable dtSerial_Seating = BaseBuildSql.GetDataTableBySql(@"SELECT   IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '41%' ");
                DataTable dtSerial_MCG = BaseBuildSql.GetDataTableBySql(@"SELECT  IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '47%' ");
                DataTable dtSerial_T = BaseBuildSql.GetDataTableBySql(@"SELECT  IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '46%' ");
                DataTable dtSerial_G = BaseBuildSql.GetDataTableBySql(@"SELECT  IDNO,[Routing_Group],[Calculate],[Calculate_Desc] FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] where 1=1 and Routing_Group like '48%' ");
                DataRow drser_Laminate = dtSerial_Laminate.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                DataRow drser_Panel = dtSerial_Panel.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                DataRow drser_Seating = dtSerial_Seating.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                DataRow drser_MCG = dtSerial_MCG.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                DataRow drser_G = dtSerial_G.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                DataTable dtAllowanceFactor = BaseBuildSql.GetDataTableBySql(@"SELECT [PROCESS_CODE],[ALLOWANCE_FACTOR] ,[EFFECTIVE_DATE],[EXPIRY_DATE] FROM [LamexMESManager].[dbo].[IE_WorkCenter_AllowanceFactor]");

                string firstCode = "";
                string secodeCode = "";
                int ifirst = 0;

                bool first_1 = true, first_2 = true, first_3 = true, first_4 = true, first_5 = true, first_6 = true;//用于判断是否第一次执行
                int Serial = 0, Routing_Group = 0, Calculate = 0;//代码组和流水号计数
                int s = 1;//序列号初始值
                          //string rountingCode = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {


                    DataRow dr = dtresult.NewRow();
                    int GROUP_CODE = 0, iCount = 0;
                    dr["DWG_NO"] = dt.Rows[i]["DWG_NO"].ToString();
                    dr["PART_NO"] = dt.Rows[i]["PART_NO"].ToString();
                    dr["CN_DESC"] = dt.Rows[i]["CN_DESC"].ToString();

                    DataRow[] drow = dtAllowanceFactor.Select("PROCESS_CODE='" + dt.Rows[i]["PROCESS_CODE"].ToString() + "'");
                    if (drow.Count() != 0)
                    {
                        string allowanceFactory = dtAllowanceFactor.Select("PROCESS_CODE='" + dt.Rows[i]["PROCESS_CODE"].ToString() + "'").CopyToDataTable().Rows[0]["ALLOWANCE_FACTOR"].ToString();
                        dr["LABOR_VALUE"] = Math.Ceiling(Convert.ToDouble(dt.Rows[i]["LABOR_VALUE"].ToString()) * (1 + Convert.ToDouble(allowanceFactory)));
                    }
                    else
                    {
                        dr["LABOR_VALUE"] = 0;
                    }
                    if (dt.Rows[i]["GROUP_CODE"].ToString() != "")
                        dr["TypeName"] = dt.Rows[i]["GROUP_CODE"].ToString().Substring(0, 1);
                    dr["GROUP"] = dt.Rows[i]["GROUP_CODE"].ToString();
                    dr["GROUP_CODE"] = GROUP_CODE;
                    dr["iCount"] = iCount;

                    dr["PROCESS_CODE"] = dt.Rows[i]["PROCESS_CODE"].ToString();
                    dr["ALLOWANCE_FACTOR"] = dt.Rows[i]["ALLOWANCE_FACTOR"].ToString();
                    dr["UPDATE_USER"] = dt.Rows[i]["UPDATE_USER"].ToString();


                    dr["UPDATE_TIME"] = dt.Rows[i]["UPDATE_TIME"].ToString();
                    dtresult.Rows.Add(dr);

                }

                int Msg = 0;

                DataView dv = new DataView(dtresult);
                DataTable dtList = dv.ToTable(true, new string[] { "DWG_NO", "PART_NO", "GROUP" });
                DataTable dtMerger = dtresult.Clone();
                dtTemp.Clear();
                foreach (DataRow dr in dtList.Rows)
                {
                    string ErrorMsg = "";
                    string ErrorMsg2 = "";
                    DataTable dt_R = BaseBuildSql.GetDataTableBySql(" SELECT ROUTING_CODE FROM [LamexMESManager].[dbo].[IE_Routing_Combination] WHERE GROUP_CODE='" + dr["GROUP"].ToString() + "'");
                    if (dt_R.Rows.Count <= 0)
                    {
                        //DevExpress.XtraEditors.XtraMessageBox.Show("部件号【" + dr["PART_NO"] + "】没有工艺路线【" + dr["GROUP_CODE"].ToString() + "】！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ErrorMsg = "部件号【" + dr["PART_NO"] + "】没有工艺路线【" + dr["GROUP"].ToString() + "】！";
                        //Msg++;
                    }
                    if (dtList.Rows.Count != 0)
                    {
                        DataRow[] drs = dtresult.Select(" 1=1 and PART_NO='" + dr["PART_NO"] + "'");
                        DataTable cycledt = BaseBuildSql.GetDataTableBySql(" select CYCLE_TIME from IE_Part_CycleTime where PART_NO='" + dr["PART_NO"].ToString() + "'");
                        if (cycledt.Rows.Count == 0)
                        {

                            ErrorMsg = "无生产周期;";
                            //Msg++;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(cycledt.Rows[0]["CYCLE_TIME"].ToString()))
                            {
                                ErrorMsg = "无生产周期;";
                                //Msg++;
                            }
                        }


                        if (drs.Count() != 0)
                        {
                            string rountinName = dr["GROUP"].ToString();
                            double value = 0;
                            DataTable dtcombin = BaseBuildSql.GetDataTableBySql(" select * from IE_Routing_Combination where GROUP_CODE='" + rountinName + "' ");
                            if (dtcombin.Rows.Count != 0)
                            {
                                string[] arr = dtcombin.Rows[0]["ROUTING_CODE"].ToString().Split('_');
                                if (arr.Count() != drs.Count())
                                {
                                    ErrorMsg += "工作中心数目不一致或工作中心特征时间不一致;";
                                }
                                int i = 0;
                                foreach (string ss in arr)
                                {

                                    foreach (DataRow d in drs)
                                    {
                                        if (ss == d["PROCESS_CODE"].ToString())
                                        {
                                            i++;
                                            if (i == 1)
                                            {
                                                d["SERIAL"] = 10;
                                            }
                                            else
                                            {
                                                d["SERIAL"] = i * 10;

                                            }
                                            rountinName += "_" + d["LABOR_VALUE"].ToString();
                                        }

                                    }


                                }
                            }
                            int m = 0;
                            foreach (DataRow d in drs)
                            {

                                if (Convert.ToDouble(d["LABOR_VALUE"].ToString()) == 0)
                                {
                                    m++;
                                    value = Convert.ToDouble(d["LABOR_VALUE"].ToString());
                                    ErrorMsg += d["PROCESS_CODE"] + ",";
                                    ErrorMsg2 += d["PROCESS_CODE"] + ",";
                                }
                            }
                            if (ErrorMsg.Length > 3) Msg++;
                            if (!string.IsNullOrEmpty(ErrorMsg))
                            {
                                ErrorMsg = ErrorMsg.Substring(0, ErrorMsg.Length - 1);
                                if (m != 0) ErrorMsg += "特征为0";
                                //ErrorMsg += "特征为0";
                                foreach (DataRow _d in drs)
                                {
                                    DataRow d = dtMerger.NewRow();
                                    d["DWG_NO"] = _d["DWG_NO"].ToString();
                                    d["PART_NO"] = _d["PART_NO"].ToString();
                                    d["CN_DESC"] = _d["CN_DESC"].ToString();
                                    d["CountDecription"] = rountinName;
                                    d["LABOR_VALUE"] = _d["LABOR_VALUE"];
                                    d["GROUP"] = _d["GROUP"];
                                    d["GROUP_CODE"] = _d["GROUP_CODE"];
                                    d["iCount"] = _d["iCount"];
                                    d["SERIAL"] = _d["SERIAL"];
                                    d["PROCESS_CODE"] = _d["PROCESS_CODE"];
                                    d["ALLOWANCE_FACTOR"] = _d["ALLOWANCE_FACTOR"];
                                    d["UPDATE_USER"] = _d["UPDATE_USER"];
                                    d["UPDATE_TIME"] = _d["UPDATE_TIME"];
                                    d["ErrorMsg"] = ErrorMsg;
                                    dtMerger.Rows.Add(d);
                                }
                            }
                            else
                            {
                                int iSequence = 0;
                                string[] arr = rountinName.Split('_');
                                DataTable dtRounting = BaseBuildSql.GetDataTableBySql(" select * from [IE_Routing_Combination] where GROUP_CODE='" + arr[0].ToString() + "' ");

                                DataRow[] drows = drs.OrderBy(x => x["SERIAL"]).ToArray();
                                foreach (DataRow _d in drows)
                                {
                                    int GROUP_CODE1 = 0, iCount1 = 0;
                                    #region 获取计数流水和组别
                                    if (_d["TypeName"].ToString() == "D") //Laminate
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_Laminate, dtRouting, drser_Laminate, drRouting, first_1, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 1, out GROUP_CODE1, out iCount1);
                                        first_1 = false;
                                    }
                                    if (_d["TypeName"].ToString() == "P")//Panel
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_Panel, dtRouting, drser_Panel, drRouting, first_2, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 2, out GROUP_CODE1, out iCount1);
                                        first_2 = false;
                                    }
                                    if (_d["TypeName"].ToString() == "S")//Seating
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_Seating, dtRouting, drser_Seating, drRouting, first_3, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 3, out GROUP_CODE1, out iCount1);
                                        first_3 = false;
                                    }
                                    if (_d["TypeName"].ToString() == "M")//MCG
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_MCG, dtRouting, drser_MCG, drRouting, first_4, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 4, out GROUP_CODE1, out iCount1);
                                        first_4 = false;
                                    }
                                    if (_d["TypeName"].ToString() == "T")///
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_T, dtRouting, drser_MCG, drRouting, first_5, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 5, out GROUP_CODE1, out iCount1);
                                        first_5 = false;
                                    }
                                    else if (_d["TypeName"].ToString() == "G")//G
                                    {
                                        Common.GetSerial_No.Serial_No(dtSerial_G, dtRouting, drser_G, drRouting, first_6, int.Parse(_d["SERIAL"].ToString()), Routing_Group, Calculate, rountinName, 6, out GROUP_CODE1, out iCount1);
                                        first_6 = false;
                                    }

                                    _d["GROUP_CODE"] = GROUP_CODE1;
                                    _d["iCount"] = iCount1;
                                    #endregion


                                    DataRow d = dtMerger.NewRow();
                                    d["DWG_NO"] = _d["DWG_NO"].ToString();
                                    d["PART_NO"] = _d["PART_NO"].ToString();
                                    d["CN_DESC"] = _d["CN_DESC"].ToString();
                                    d["CountDecription"] = rountinName;
                                    d["LABOR_VALUE"] = _d["LABOR_VALUE"];
                                    d["GROUP"] = _d["GROUP"];
                                    d["GROUP_CODE"] = _d["GROUP_CODE"];
                                    d["iCount"] = _d["iCount"];
                                    d["SERIAL"] = _d["SERIAL"];
                                    d["PROCESS_CODE"] = _d["PROCESS_CODE"];
                                    d["ALLOWANCE_FACTOR"] = _d["ALLOWANCE_FACTOR"];
                                    d["UPDATE_USER"] = _d["UPDATE_USER"];
                                    d["UPDATE_TIME"] = _d["UPDATE_TIME"];
                                    d["ErrorMsg"] = "成功";
                                    dtMerger.Rows.Add(d);


                                    DataRow drow = dtTemp.NewRow();
                                    drow["图纸号"] = _d["DWG_NO"].ToString();
                                    drow["部件编号"] = _d["PART_NO"].ToString();
                                    drow["工序组"] = _d["GROUP_CODE"];
                                    drow["计数器"] = _d["iCount"];
                                    drow["计数器描述"] = rountinName;
                                    drow["序号"] = _d["SERIAL"];
                                    drow["工序代码"] = _d["PROCESS_CODE"];
                                    drow["工序工时(S)"] = _d["LABOR_VALUE"];

                                    if (dtRounting.Rows[0]["PARALLEL_PROCESS"].ToString().Length > 0)
                                    {
                                        string RountingArr = dtRounting.Rows[0]["PARALLEL_PROCESS"].ToString();
                                        if (RountingArr.Contains(_d["PROCESS_CODE"].ToString()))
                                        {
                                            iSequence++;
                                            drow["并行标识"] = iSequence;
                                        }
                                        else
                                        {
                                            drow["并行标识"] = 0;
                                        }

                                    }
                                    else
                                    {
                                        drow["并行标识"] = 0;
                                    }
                                    dtTemp.Rows.Add(drow);
                                }
                            }

                        }
                    }

                }

                //批量保存dtRouting
                if (dtRouting.Rows.Count != 0)
                {
                    DataRow[] _drows = dtRouting.Select("Routing_Group<>'0'");
                    if (_drows.Count() != 0)
                    {
                        DataTable dtsave = _drows.CopyToDataTable();

                        if (BaseBuildSql.ExcuteInsert(dtsave, "B_IE_Calculator_Routing"))
                        {
                            dtRouting = new DataTable();
                        }
                    }
                }
                gridControl1.DataSource = null;
                gridView1.Columns.Clear();
                
                gridControl1.DataSource = dtMerger;
                this.gridView1.Columns["GROUP"].Visible = false;
                this.gridView1.Columns["TypeName"].Visible = false;
                this.gridView1.OptionsView.ColumnAutoWidth = false;
                gridView1.BestFitColumns();
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show("【工时成功计算数目：" + (dtList.Rows.Count - Msg) + "】/【工时失败计算数目：" + Msg + "】");
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }

            
            base.DoIECalcuate(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "Excel (2003)(.xls)|*.xls";
            if (saveFile.ShowDialog()==DialogResult.OK)
            {
                string exportFilePath = saveFile.FileName;
                string fileExtenstion = new FileInfo(exportFilePath).Extension;
                gridView1.ExportToXls(saveFile.FileName);
            }
            base.DoExport(sender);
        }

        private void sbtnIECalculate_Click(object sender, EventArgs e)
        {
            DoIECalcuate(null);
        }

        private void sbtnIEExportUpLoad_Click(object sender, EventArgs e)
        {
            DoIEExportUpLoad(null);
        }
    }
}
